'use client';

import { useState, useEffect, Fragment, useRef } from 'react';
import { Question } from '@/types';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';

interface Props {
  categoryId: string;
  onComplete: () => void;
  onCancel: () => void;
  fillOnly?: boolean; // 是否为拼写纯享版（仅填空）
}

export default function Challenge({ categoryId, onComplete, onCancel, fillOnly }: Props) {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [userAnswers, setUserAnswers] = useState<string[]>([]);
  const [selectedOptionIndexes, setSelectedOptionIndexes] = useState<(number | null)[]>([]);
  const [startTime, setStartTime] = useState<number>(0);
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [showCards, setShowCards] = useState(false);
  const [viewingCardIndex, setViewingCardIndex] = useState(0);
  const [now, setNow] = useState(Date.now());
  // 用于管理每个输入框的 ref 和当前聚焦索引
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const [focusedInputIndex, setFocusedInputIndex] = useState<number>(0);

  useEffect(() => {
    startChallenge();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 当题目切换时，自动聚焦第一个输入框
  useEffect(() => {
    if (!loading && questions.length > 0) {
      const currentQuestion = questions[currentIndex];
      if (currentQuestion?.type === 'fill-in') {
        setFocusedInputIndex(0);
        // 延迟聚焦，确保 DOM 已更新
        const timer = setTimeout(() => {
          const firstInput = inputRefs.current[0];
          if (firstInput) {
            firstInput.focus();
          }
        }, 100);
        return () => clearTimeout(timer);
      }
    }
  }, [currentIndex, loading, questions.length]);

  // tick every second during active challenge to update elapsed time
  useEffect(() => {
    if (loading || result) return;
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, [loading, result]);

  // 键盘快捷键支持（上下键）
  useEffect(() => {
    if (loading || result || showCards || questions.length === 0) return;
    
    const handleKeyDown = (e: KeyboardEvent) => {
      // 如果正在输入框中，不触发快捷键
      if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
        return;
      }
      
      if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (currentIndex > 0) {
          handlePrev();
        }
      } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        const isFillIn = questions[currentIndex]?.type === 'fill-in';
        const nextDisabled = isFillIn
          ? (userAnswers[currentIndex] || '').trim() === ''
          : selectedOptionIndexes[currentIndex] === null;
        
        if (!nextDisabled) {
          handleNext();
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentIndex, loading, result, showCards, questions.length, userAnswers, selectedOptionIndexes]);

  const startChallenge = async () => {
    try {
      const res = await fetch('/api/challenge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ categoryId, action: 'generate', mode: fillOnly ? 'fill-only' : undefined }),
      });

      const data = await res.json();
      if (data.success) {
        setQuestions(data.questions);
        setUserAnswers(new Array(data.questions.length).fill(''));
        setSelectedOptionIndexes(new Array(data.questions.length).fill(null));
        setStartTime(Date.now());
      } else {
        alert(data.message);
        onCancel();
      }
    } catch (error) {
      alert('生成挑战失败');
      onCancel();
    } finally {
      setLoading(false);
    }
  };

  const handleAnswer = (answer: string, optionIndex: number | null) => {
    const newAnswers = [...userAnswers];
    newAnswers[currentIndex] = answer;
    setUserAnswers(newAnswers);

    const newIndexes = [...selectedOptionIndexes];
    newIndexes[currentIndex] = optionIndex;
    setSelectedOptionIndexes(newIndexes);
  };

  const handleFillInChange = (value: string) => {
    const newAnswers = [...userAnswers];
    newAnswers[currentIndex] = value;
    setUserAnswers(newAnswers);

    const newIndexes = [...selectedOptionIndexes];
    newIndexes[currentIndex] = null;
    setSelectedOptionIndexes(newIndexes);
  };

  // Fill-in helpers (per-word inputs)
  const getWordSpans = (text: string): { start: number; end: number }[] => {
    const spans: { start: number; end: number }[] = [];
    let i = 0;
    while (i < text.length) {
      while (i < text.length && text[i] === ' ') i++;
      if (i >= text.length) break;
      const start = i;
      while (i < text.length && text[i] !== ' ') i++;
      const end = i; // [start, end)
      spans.push({ start, end });
    }
    return spans;
  };

  const setAnswerWordAt = (spanIndex: number, value: string, target: string, previousValue?: string) => {
    const spans = getWordSpans(target);
    const span = spans[spanIndex];
    if (!span) return;
    const raw = (userAnswers[currentIndex] || '').padEnd(target.length, ' ');
    const wordLen = span.end - span.start;
    const limited = value.slice(0, wordLen);
    const filled = limited.padEnd(wordLen, ' ');
    const next = raw.slice(0, span.start) + filled + raw.slice(span.end, target.length);
    handleFillInChange(next);

    // 智能跳转逻辑
    const isDeleting = previousValue !== undefined && value.length < previousValue.length;
    const isFilled = limited.length === wordLen;
    const isEmpty = limited.length === 0;

    // 如果输入完成（填满），自动跳到下一个
    if (!isDeleting && isFilled && spanIndex < spans.length - 1) {
      setTimeout(() => {
        const nextInput = inputRefs.current[spanIndex + 1];
        if (nextInput) {
          nextInput.focus();
          setFocusedInputIndex(spanIndex + 1);
        }
      }, 0);
    }
    // 如果删除到空，自动跳回上一个
    else if (isDeleting && isEmpty && spanIndex > 0) {
      setTimeout(() => {
        const prevInput = inputRefs.current[spanIndex - 1];
        if (prevInput) {
          prevInput.focus();
          setFocusedInputIndex(spanIndex - 1);
        }
      }, 0);
    }
  };

  

  

  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const mq = typeof window !== 'undefined' ? window.matchMedia('(max-width: 600px)') : null;
    const update = () => setIsMobile(!!mq?.matches);
    update();
    mq?.addEventListener('change', update);
    return () => mq?.removeEventListener('change', update);
  }, []);

  const splitWords = (text: string) => text.trim().split(/\s+/).filter(Boolean);


  const renderMaskedWord = (value: string) => {
    const words = splitWords(value);
    if (words.length === 0) return null;
    // 单词：加粗放大
    if (words.length === 1) {
      return (
        <div style={{ textAlign: 'center', whiteSpace: 'pre-wrap', fontSize: '36px', fontWeight: 'bold', letterSpacing: isMobile ? '4px' : '2px' }}>
          {words[0]}
        </div>
      );
    }
    // 短语：按空格分词，每个词使用下虚线
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          gap: '12px',
          flexWrap: 'wrap',
          fontSize: '32px',
          fontWeight: 'bold',
          letterSpacing: isMobile ? '4px' : '2px'
        }}
      >
        {words.map((w, i) => (
          <span
            key={i}
            style={{
              padding: '0 6px',
              borderBottom: '3px dashed rgba(0,0,0,0.3)',
              lineHeight: 1.6,
            }}
          >
            {w}
          </span>
        ))}
      </div>
    );
  };

  const handleNext = () => {
    if (currentIndex < questions.length - 1) {
      setCurrentIndex(currentIndex + 1);
      // 进入下一题时，重置聚焦索引
      setFocusedInputIndex(0);
      // 进入下一题时，根据已存索引恢复高亮
      // 无需设置字符串答案用于高亮，完全依据索引
    } else {
      submitChallenge();
    }
  };

  const handlePrev = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
      // 返回上一题时，重置聚焦索引
      setFocusedInputIndex(0);
      // 返回上一题时，根据已存索引恢复高亮
    }
  };

  const submitChallenge = async () => {
    const timeSpent = Math.floor((Date.now() - startTime) / 1000);
    
    try {
      const res = await fetch('/api/challenge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          categoryId,
          action: 'submit',
          questions,
          userAnswers,
          timeSpent,
        }),
      });

      const data = await res.json();
      if (data.success) {
        setResult(data.record);
      } else {
        alert('提交失败');
      }
    } catch (error) {
      alert('提交失败');
    }
  };

  if (loading) {
    return (
      <div className="card">
        <div>加载中...</div>
      </div>
    );
  }

  if (result) {
    const score = result.score;
    const timeSpent = result.timeSpent;
    const points = result.points;
    const totalQuestions = result.questions.length;
    const isPerfect = score === totalQuestions;
    const wrongQuestions = result.questions.filter((q: Question) => !q.isCorrect);
    const cardsToShow = isPerfect ? result.questions : wrongQuestions;

    // 根据错误程度获取文案
    const getFeedbackMessage = () => {
      if (isPerfect) {
        return {
          title: '🎉 太棒了！',
          message: '恭喜你完美通关！所有题目都答对了，继续保持！',
        };
      }
      const wrongCount = totalQuestions - score;
      if (wrongCount <= 1) {
        return {
          title: '💪 很不错！',
          message: '你已经很接近完美了，只错了1题。继续加油，相信下次就能全对！',
        };
      } else if (wrongCount <= 3) {
        return {
          title: '👍 还不错！',
          message: `你答对了 ${score} 题，表现不错！但还有 ${wrongCount} 题需要加强，多练习会更好。`,
        };
      } else if (wrongCount <= 6) {
        return {
          title: '📚 需要多练习',
          message: `你答对了 ${score} 题，还有 ${wrongCount} 题需要加强。建议多复习这些单词，下次一定能做得更好！`,
        };
      } else {
        return {
          title: '💪 继续努力',
          message: `你答对了 ${score} 题，还有 ${wrongCount} 题需要加强。不要灰心，多练习这些单词，相信你会越来越好的！`,
        };
      }
    };

    const feedback = getFeedbackMessage();

    // 如果正在查看卡片
    if (showCards && cardsToShow.length > 0) {
      const currentCard = cardsToShow[viewingCardIndex];
      const isWrong = !currentCard.isCorrect;

      return (
        <Card className="w-full max-w-2xl mx-auto">
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle>
                {isPerfect ? '🌟 查看所有卡片' : '⭐ 错误题目回顾'}
              </CardTitle>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowCards(false)}
              >
                返回
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center text-muted-foreground">
              题目 {viewingCardIndex + 1} / {cardsToShow.length}
            </div>

            <div>
              <h3 className="text-2xl font-semibold text-center mb-6">
                {currentCard.type === 'fill-in'
                  ? '请根据提示补全英文单词'
                  : currentCard.type === 'en-to-cn'
                    ? '请选择中文含义'
                    : '请选择英文单词'}
              </h3>
            {currentCard.type === 'fill-in' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px', alignItems: 'center' }}>
            <div style={{
                  marginBottom: '10px',
                  padding: '20px',
                  backgroundColor: '#f5f5f5',
                  borderRadius: '8px',
                  width: '100%',
                }}>
              {renderMaskedWord(currentCard.maskedWord || currentCard.correctAnswer.replace(/[a-zA-Z]/g, '_'))}
                </div>
            {/* phrase word count hint removed */}
                <div style={{
                  fontSize: '18px',
                  textAlign: 'center',
                  color: '#555',
                }}>
                  提示：{currentCard.question}
                </div>
                <div style={{
                  padding: '15px',
                  backgroundColor: currentCard.isCorrect ? '#e8f5e9' : '#fff3cd',
                  borderRadius: '8px',
                  border: `1px solid ${currentCard.isCorrect ? '#4caf50' : '#ffc107'}`,
                  width: '100%',
                }}>
                  <div><strong>正确答案：</strong>{currentCard.correctAnswer}</div>
                  <div><strong>你的答案：</strong>{currentCard.userAnswer || '未作答'}</div>
                </div>
              </div>
            ) : (
              <>
            <div style={{
              fontSize: '32px',
              fontWeight: 'bold',
              textAlign: 'center',
              marginBottom: '30px',
              padding: '20px',
              backgroundColor: '#f5f5f5',
              borderRadius: '8px',
            }}>
              {currentCard.question}
            </div>

            <div style={{ display: 'grid', gap: '15px', marginBottom: '20px' }}>
                  {currentCard.options?.map((option: string, index: number) => {
                const isCorrect = option === currentCard.correctAnswer;
                const isUserAnswer = option === currentCard.userAnswer;
                let backgroundColor = 'white';
                let borderColor = '#ddd';
                let color = '#333';

                if (isCorrect && isUserAnswer) {
                  backgroundColor = '#4caf50';
                  borderColor = '#4caf50';
                  color = 'white';
                } else if (isCorrect && !isUserAnswer) {
                  backgroundColor = '#4caf50';
                  borderColor = '#4caf50';
                  color = 'white';
                } else if (!isCorrect && isUserAnswer) {
                  backgroundColor = '#f44336';
                  borderColor = '#f44336';
                  color = 'white';
                }

                return (
                  <div
                    key={index}
                    style={{
                      padding: '15px',
                      fontSize: '18px',
                      backgroundColor,
                      color,
                      border: `2px solid ${borderColor}`,
                      borderRadius: '8px',
                      textAlign: 'left',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '10px',
                    }}
                  >
                    <span>{String.fromCharCode(65 + index)}.</span>
                    <span>{option}</span>
                    {isCorrect && isUserAnswer && <span style={{ marginLeft: 'auto' }}>✓ 你的答案（正确）</span>}
                    {isCorrect && !isUserAnswer && <span style={{ marginLeft: 'auto' }}>✓ 正确答案</span>}
                    {!isCorrect && isUserAnswer && <span style={{ marginLeft: 'auto' }}>✗ 你的选择</span>}
                  </div>
                );
              })}
            </div>

            {isWrong && (
              <div style={{
                padding: '15px',
                backgroundColor: '#fff3cd',
                borderRadius: '8px',
                border: '1px solid #ffc107',
                marginBottom: '20px',
              }}>
                <div><strong>正确答案：</strong>{currentCard.correctAnswer}</div>
                <div><strong>你的答案：</strong>{currentCard.userAnswer || '未作答'}</div>
              </div>
                )}
              </>
            )}
          </div>

            <div className="flex gap-3 justify-between mt-6">
              <Button
                variant="secondary"
                onClick={() => setViewingCardIndex(Math.max(0, viewingCardIndex - 1))}
                disabled={viewingCardIndex === 0}
                className="flex-1"
              >
                上一题
              </Button>
              {viewingCardIndex < cardsToShow.length - 1 ? (
                <Button
                  onClick={() => setViewingCardIndex(viewingCardIndex + 1)}
                  className="flex-1"
                >
                  下一题
                </Button>
              ) : (
                <Button
                  variant="outline"
                  onClick={() => setShowCards(false)}
                  className="flex-1"
                >
                  返回
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      );
    }

    // 显示结果页面
    return (
      <Card className="w-full max-w-2xl mx-auto">
        <CardHeader>
          <CardTitle className="text-center text-3xl">{feedback.title}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className={`p-4 rounded-lg border ${
            isPerfect 
              ? 'bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800' 
              : 'bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800'
          }`}>
            <p className={`text-center text-base leading-relaxed ${
              isPerfect 
                ? 'text-green-900 dark:text-green-100' 
                : 'text-orange-900 dark:text-orange-100'
            }`}>
              {feedback.message}
            </p>
          </div>

          <div className="text-center space-y-4">
            <div className={`text-6xl font-bold ${
              isPerfect ? 'text-green-600 dark:text-green-400' : 'text-primary'
            }`}>
              {score}/{totalQuestions}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
              <div className="p-4 bg-card border border-border rounded-lg">
                <div className="text-sm text-muted-foreground mb-1">得分</div>
                <div className="text-2xl font-bold">{score} 分</div>
              </div>
              <div className="p-4 bg-card border border-border rounded-lg">
                <div className="text-sm text-muted-foreground mb-1">耗时</div>
                <div className="text-2xl font-bold">{timeSpent} 秒</div>
              </div>
              <div className="p-4 bg-card border border-border rounded-lg">
                <div className="text-sm text-muted-foreground mb-1">获得积分</div>
                <div className="text-2xl font-bold">{points} 分</div>
              </div>
            </div>
          </div>

          <div className="flex gap-3 justify-center flex-wrap pt-4">
            <Button
              onClick={() => {
                setShowCards(true);
                setViewingCardIndex(0);
              }}
            >
              {isPerfect ? ' 查看所有卡片' : ' 查看错误题目'}
            </Button>
            <Button
              variant="default"
              onClick={async () => {
                // 重置所有状态
                setResult(null);
                setShowCards(false);
                setViewingCardIndex(0);
                setCurrentIndex(0);
                setUserAnswers([]);
                setSelectedOptionIndexes([]);
                setFocusedInputIndex(0);
                setLoading(true);
                // 重新开始挑战
                await startChallenge();
              }}
            >
               重新挑战
            </Button>
            <Button
              variant="secondary"
              onClick={onComplete}
            >
              返回
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  const currentQuestion = questions[currentIndex];
  if (!currentQuestion) {
    return (
      <div className="card">
        <div>加载中...</div>
      </div>
    );
  }
  const isFillIn = currentQuestion.type === 'fill-in';
  const progress = ((currentIndex + 1) / questions.length) * 100;
  const isNextDisabled = isFillIn
    ? userAnswers[currentIndex].trim() === ''
    : selectedOptionIndexes[currentIndex] === null;

  return (
    <div className="card">
      <div className="flex justify-between items-center mb-3">
        <span className="font-semibold text-lg">挑战进行中</span>
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            if (confirm('确定要退出本次挑战吗？已答内容将不会保存。')) {
              onCancel();
            }
          }}
          className="text-destructive hover:text-destructive hover:bg-destructive/10"
        >
          退出挑战
        </Button>
      </div>
      <div style={{ marginBottom: '20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '10px' }}>
          <span>题目 {currentIndex + 1} / {questions.length}</span>
          <span>耗时: {Math.floor((now - startTime) / 1000)} 秒</span>
        </div>
        <div style={{
          width: '100%',
          height: '10px',
          backgroundColor: '#e0e0e0',
          borderRadius: '5px',
          overflow: 'hidden',
        }}>
          <div style={{
            width: `${progress}%`,
            height: '100%',
            backgroundColor: '#0070f3',
            transition: 'width 0.3s',
          }} />
        </div>
      </div>

      <div style={{ marginBottom: '30px' }}>
        <h3 style={{ marginBottom: '20px', fontSize: '24px', textAlign: 'center' }}>
          {isFillIn
            ? '请根据提示补全英文单词'
            : currentQuestion.type === 'en-to-cn'
              ? '请选择中文含义'
              : '请选择英文单词'}
        </h3>

        {isFillIn ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px', alignItems: 'center' }}>
            <div style={{
              marginBottom: '10px',
              padding: '20px',
              backgroundColor: '#f5f5f5',
              borderRadius: '8px',
              width: '100%',
            }}>
              {renderMaskedWord(currentQuestion.maskedWord || currentQuestion.correctAnswer.replace(/[a-zA-Z]/g, '_'))}
            </div>
            {/* phrase word count hint removed */}
            <div style={{
              fontSize: '18px',
              textAlign: 'center',
              color: '#555',
            }}>
              提示：{currentQuestion.question}
            </div>
            {(() => {
              const target = currentQuestion.correctAnswer;
              const spans = getWordSpans(target);
              const current = (userAnswers[currentIndex] || '').padEnd(target.length, ' ');
              
              // 确保 refs 数组长度正确
              if (inputRefs.current.length !== spans.length) {
                inputRefs.current = new Array(spans.length).fill(null);
              }

              return (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', justifyContent: 'center' }}>
                  {spans.map((sp, i) => {
                    const length = sp.end - sp.start;
                    const value = current.slice(sp.start, sp.end).trim();
                    const isFocused = focusedInputIndex === i;
                    return (
                      <input
                        key={i}
                        ref={(el) => {
                          inputRefs.current[i] = el;
                        }}
                        type="text"
                        inputMode="text"
                        maxLength={length}
                        value={value}
                        onChange={(e) => {
                          const newValue = e.target.value.replace(/\s/g, '');
                          const oldValue = value;
                          setAnswerWordAt(i, newValue, target, oldValue);
                        }}
                        onFocus={() => setFocusedInputIndex(i)}
                        onKeyDown={(e) => {
                          // 支持 Backspace 删除时跳转
                          if (e.key === 'Backspace' && value.length === 0 && i > 0) {
                            e.preventDefault();
                            const prevInput = inputRefs.current[i - 1];
                            if (prevInput) {
                              prevInput.focus();
                              setFocusedInputIndex(i - 1);
                              // 选中上一个输入框的内容，方便删除
                              prevInput.select();
                            }
                          }
                          // 支持方向键在输入框间导航（不在输入框内移动光标）
                          else if (e.key === 'ArrowLeft') {
                            // 如果光标在输入框开头，或者输入框为空，跳转到上一个输入框
                            const input = e.target as HTMLInputElement;
                            const cursorPosition = input.selectionStart || 0;
                            
                            if (cursorPosition === 0 && i > 0) {
                              e.preventDefault();
                              const prevInput = inputRefs.current[i - 1];
                              if (prevInput) {
                                prevInput.focus();
                                setFocusedInputIndex(i - 1);
                                // 将光标移到上一个输入框的末尾
                                setTimeout(() => {
                                  prevInput.setSelectionRange(prevInput.value.length, prevInput.value.length);
                                }, 0);
                              }
                            }
                            // 如果不在开头，允许默认行为（在输入框内移动光标）
                          }
                          else if (e.key === 'ArrowRight') {
                            // 如果光标在输入框末尾，或者输入框为空，跳转到下一个输入框
                            const input = e.target as HTMLInputElement;
                            const cursorPosition = input.selectionStart || 0;
                            const inputLength = input.value.length;
                            
                            if ((cursorPosition === inputLength || inputLength === 0) && i < spans.length - 1) {
                              e.preventDefault();
                              const nextInput = inputRefs.current[i + 1];
                              if (nextInput) {
                                nextInput.focus();
                                setFocusedInputIndex(i + 1);
                                // 将光标移到下一个输入框的开头
                                setTimeout(() => {
                                  nextInput.setSelectionRange(0, 0);
                                }, 0);
                              }
                            }
                            // 如果不在末尾，允许默认行为（在输入框内移动光标）
                          }
                        }}
                        style={{
                          width: Math.max(36, length * 22) + 'px',
                          height: '42px',
                          textAlign: 'center',
                          fontSize: '20px',
                          padding: 0,
                          border: 'none',
                          borderBottom: isFocused 
                            ? '3px solid #0070f3' 
                            : '3px solid rgba(0,0,0,0.3)',
                          outline: 'none',
                          background: 'transparent',
                          transition: 'border-color 0.2s',
                        }}
                      />
                    );
                  })}
                </div>
              );
            })()}
          </div>
        ) : (
          <>
        <div style={{
          fontSize: '32px',
          fontWeight: 'bold',
          textAlign: 'center',
          marginBottom: '30px',
          padding: '20px',
          backgroundColor: '#f5f5f5',
          borderRadius: '8px',
        }}>
          {currentQuestion.question}
        </div>

        <div style={{ display: 'grid', gap: '15px' }}>
              {currentQuestion.options?.map((option, index) => (
            <button
              key={index}
              className="btn"
              style={{
                padding: '15px',
                fontSize: '18px',
                backgroundColor: selectedOptionIndexes[currentIndex] === index ? '#0070f3' : 'white',
                color: selectedOptionIndexes[currentIndex] === index ? 'white' : '#333',
                border: selectedOptionIndexes[currentIndex] === index ? '2px solid #0070f3' : '2px solid #ddd',
                textAlign: 'left',
              }}
              onClick={() => handleAnswer(option, index)}
            >
              {String.fromCharCode(65 + index)}. {option}
            </button>
          ))}
        </div>
          </>
        )}
      </div>

      <div className="flex gap-3 justify-between mt-6">
        <Button
          variant="secondary"
          onClick={handlePrev}
          disabled={currentIndex === 0}
          className="flex-1"
        >
          上一题
        </Button>
        <Button
          onClick={handleNext}
          disabled={isNextDisabled}
          className="flex-1"
        >
          {currentIndex === questions.length - 1 ? '提交' : '下一题 '}
        </Button>
      </div>
      {/* <div className="mt-3 text-center text-xs text-muted-foreground">
        💡 提示：可以使用 ↑ ↓ 方向键切换题目
      </div> */}
    </div>
  );
}

